﻿Public Class RawDirectroyPickerVm
    Inherits KeyedViewModelBase

    Public Sub New()
        RawDirectoryPath = My.Settings.LastRawDirectory
        mRecentDirectories = New RangeObservableCollection(Of String)
        Dim recentString As String = My.Settings.RecentRawDirectories
        If Not String.IsNullOrEmpty(recentString) Then
            mRecentDirectories.AddRange((recentString.Split({";"c}, StringSplitOptions.RemoveEmptyEntries)))
        End If
        mOkCommand = New Command(AddressOf OnOkCommand)
    End Sub

    Private mOkCommand As ICommand
    Public ReadOnly Property OkCommand As ICommand
        Get
            Return mOkCommand
        End Get
    End Property
    Public Sub OnOkCommand(param As Object)
        If IO.Directory.Exists(RawDirectoryPath) Then
            My.Settings.LastRawDirectory = RawDirectoryPath

            'Update the list of recent paths, moving the current item to the top and trimming to 10 items
            Dim recents As New List(Of String)(RecentDirectories) 'use a temp list or it will mess with the bindings
            recents.Remove(RawDirectoryPath) 'remove the current path (if it exists)
            recents.Insert(0, RawDirectoryPath) 'Insert the current path at the first position of the list
            Dim recentString As String = ""
            For i As Integer = 0 To Math.Min(9, recents.Count - 1) ' take the first 10 items from the list
                recentString = recentString & ";" & recents(i)
            Next
            My.Settings.RecentRawDirectories = recentString

            My.Settings.Save()
            SendMessage(New Messages.Common.CloseWindow)
        Else
            SendMessage(New Messages.Common.ShowSimpleMessage("Invalid Directory"))
        End If
    End Sub


    Private mRawDirectoryPath As String
    Public Property RawDirectoryPath As String
        Get
            Return mRawDirectoryPath
        End Get
        Set(value As String)
            If value <> mRawDirectoryPath Then
                mRawDirectoryPath = value
                RaisePropertyChanged("RawDirectoryPath")
            End If
        End Set
    End Property

    Private mRecentDirectories As RangeObservableCollection(Of String)
    Public Property RecentDirectories As RangeObservableCollection(Of String)
        Get
            Return mRecentDirectories
        End Get
        Set(value As RangeObservableCollection(Of String))
            If value IsNot mRecentDirectories Then
                mRecentDirectories = value
                RaisePropertyChanged("RecentDirectories")
            End If
        End Set
    End Property
End Class
